package cn.hnu.qq.client.controller;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Date;

import cn.hnu.qq.entity.ChartContent;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.ChartMessage;
import cn.hnu.qq.entity.message.DownloadMessage;
import cn.hnu.qq.entity.message.LeaveWordsMessage;
import cn.hnu.qq.global.MessageType;

public class DefaultModelChartController extends CenterController {
	
	private static DefaultModelChartController instance = null;
	
	private DefaultModelChartController(){};
	
	public static synchronized DefaultModelChartController getInstance(){
		if(instance == null){
			instance = new DefaultModelChartController();
		}
		return instance;
	}

	public void sendChartMessage(User ownner, String info) {
		ChartMessage message = new ChartMessage();
		message.setMes(info);
		message.setAccount(getCurUser().getAcount());
		byte[] datas = ObjectToArray(message);
		
		InetSocketAddress isa;
		try {
			isa = new InetSocketAddress(InetAddress.getByName(ownner.getIp()), ownner.getUserClientPort());
			DatagramPacket dp = new DatagramPacket(datas,datas.length,isa);
			getdSocket().send(dp);
			log.debug(getCurUser().getAcount()+"通过udp发送消息"+info+",发送至端口："+ownner.getIp()+":"+ownner.getUserClientPort());
		} catch (Exception e) {
			System.err.println("DefaultModelChartController sendChartMessage");
			log.error("DefaultModelChartController sendChartMessage");
			e.printStackTrace();
		}
	}

	public void sendLeaveMessage(User ownner, String info) {
		LeaveWordsMessage lwm = new LeaveWordsMessage();
		lwm.setLeaver(getCurUser().getAcount());
		lwm.setScanner(ownner.getAcount());
		lwm.setLeavingWords(info);
		try {
			getOutput().writeObject(lwm);
			getOutput().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendUploadMessage(User ownner, String string) {
		ChartContent cc = new ChartContent();
		cc.setMessageType(MessageType.UPLOAD_CHART_CONTENT);
		cc.setOwner(getCurUser());
		cc.setCharter(ownner);
		cc.setContent(string);
		cc.setTime(new Date());
		try {
			getOutput().writeObject(cc);
			getOutput().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void download(User ownner) {
		DownloadMessage dm = new DownloadMessage();
		dm.setUser(getCurUser().getAcount());
		dm.setObj(ownner.getAcount());
		dm.setType(false);
		try {
			getOutput().writeObject(dm);
			getOutput().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
